package client;

import beans.Estudiant;
import beans.TotalsPregunta;
import common.EOlympicsException;
import common.RemotInterface;
import common.TDSLanguageUtils;
import java.rmi.RemoteException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;


/**
 * Classe PantallaResultats
 * @author Juan Luís Chávez Lobato i Jesús Hernàndez Garcia
 */

public class PantallaResultats extends javax.swing.JFrame {

    private RemotInterface remot;
    private Estudiant EstLogin;

    /**
     * Creates new form PantallaResultats
     */
    public PantallaResultats(RemotInterface rem, Estudiant est) {
        try {
            remot = rem;
            EstLogin = est;
            initComponents();
            TDSLanguageUtils.setDefaultLanguage("i18n/messages");
            setTitle(TDSLanguageUtils.getMessage("titol.finestra"));
            LabelNomEst.setText(TDSLanguageUtils.getMessage("texte.NomEst"));
            LabelNomUniv.setText(TDSLanguageUtils.getMessage("texte.NomUniv"));
            
            NomEstudiant.setText(EstLogin.getNom() + " " + EstLogin.getCognoms());
            NomUniversitat.setText(remot.getNomUniversitat(EstLogin.getIdUni()));
            
            BotoSortir.setText(TDSLanguageUtils.getMessage("boto.sortir"));

            for (int i = 0; i < TaulaResultat.getColumnCount(); i++) {
              TaulaResultat.getColumnModel().getColumn(i).setHeaderValue(TDSLanguageUtils.getMessage("taula.col"+i));
            }        
            
            CheckUniversitat.setText(TDSLanguageUtils.getMessage("check.veureUniv"));
            
            // Omplirà el jTable TaulaResultat amb els resultats de la BD
            CarregaReixeta();
            
        } catch (RemoteException ex) {
            Logger.getLogger(PantallaParticipacio.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog
                    (null, TDSLanguageUtils.getMessage("ERR_REMOT"), "Error", JOptionPane.ERROR_MESSAGE);
        } catch (EOlympicsException ex) {
            Logger.getLogger(PantallaParticipacio.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        } catch (Exception ex) {
            Logger.getLogger(PantallaParticipacio.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
        
    }

    private void CarregaReixeta() {
        try {
            // Borrem la taula
            while (TaulaResultat.getRowCount() > 0) {
                ((DefaultTableModel)TaulaResultat.getModel()).removeRow(0);
            }
            
            List<TotalsPregunta> totalsPreg =
                    remot.getResultatsTotals(EstLogin.getLogin(), CheckUniversitat.isSelected());

            // Omplim la taula amb la llista de resultats de preguntes de les que hi ha enquesta
            if (totalsPreg.isEmpty()) {
                throw new EOlympicsException(TDSLanguageUtils.getMessage("missatge.nohihaenq"));
            } else {
                int fila = 0;
                for (TotalsPregunta totp : totalsPreg) {
                    // Afegim una fila a la taula.
                    ((DefaultTableModel)TaulaResultat.getModel()).addRow(new Object[]{""});
                    // Carregar les dades a la fila corresponent de la taula
                    TaulaResultat.setValueAt(totp.getPregunta(),           fila, 0);
                    TaulaResultat.setValueAt(totp.getTotalsMoltDesacord(), fila, 1);
                    TaulaResultat.setValueAt(totp.getTotalsMicaDesacord(), fila, 2);
                    TaulaResultat.setValueAt(totp.getTotalsIndiferent(),   fila, 3);
                    TaulaResultat.setValueAt(totp.getTotalsMicaAcord(),    fila, 4);
                    TaulaResultat.setValueAt(totp.getTotalsMoltAcord(),    fila, 5);
                    TaulaResultat.setValueAt(totp.getVotEstudiant(),       fila, 6);
                    fila++;
                }
            }

        } catch (RemoteException ex) {
            Logger.getLogger(PantallaParticipacio.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog
                    (null, TDSLanguageUtils.getMessage("ERR_REMOT"), "Error", JOptionPane.ERROR_MESSAGE);
        } catch (EOlympicsException ex) {
            Logger.getLogger(PantallaParticipacio.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        } catch (Exception ex) {
            Logger.getLogger(PantallaParticipacio.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
        
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        BotoSortir = new javax.swing.JButton();
        PanellEstudiant = new javax.swing.JPanel();
        LabelNomEst = new javax.swing.JLabel();
        LabelNomUniv = new javax.swing.JLabel();
        NomEstudiant = new javax.swing.JLabel();
        NomUniversitat = new javax.swing.JLabel();
        PanellResultat = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        TaulaResultat = new javax.swing.JTable();
        CheckUniversitat = new javax.swing.JCheckBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        BotoSortir.setText("Sortir");
        BotoSortir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BotoSortirActionPerformed(evt);
            }
        });

        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("i18n/messages"); // NOI18N
        PanellEstudiant.setBorder(javax.swing.BorderFactory.createTitledBorder(null, bundle.getString("panell.EstConn"), javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N
        PanellEstudiant.setFocusable(false);

        LabelNomEst.setText("Nom i cognoms :");

        LabelNomUniv.setText("Universitat :");

        NomEstudiant.setBackground(new java.awt.Color(0, 204, 204));
        NomEstudiant.setText("Nom Estudiant");
        NomEstudiant.setOpaque(true);

        NomUniversitat.setBackground(new java.awt.Color(0, 204, 204));
        NomUniversitat.setText("Nom Universitat");
        NomUniversitat.setOpaque(true);

        javax.swing.GroupLayout PanellEstudiantLayout = new javax.swing.GroupLayout(PanellEstudiant);
        PanellEstudiant.setLayout(PanellEstudiantLayout);
        PanellEstudiantLayout.setHorizontalGroup(
            PanellEstudiantLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(PanellEstudiantLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(PanellEstudiantLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(LabelNomEst)
                    .addComponent(LabelNomUniv))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(PanellEstudiantLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(NomEstudiant, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(NomUniversitat, javax.swing.GroupLayout.DEFAULT_SIZE, 353, Short.MAX_VALUE))
                .addContainerGap())
        );
        PanellEstudiantLayout.setVerticalGroup(
            PanellEstudiantLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, PanellEstudiantLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(PanellEstudiantLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(LabelNomEst)
                    .addComponent(NomEstudiant))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(PanellEstudiantLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(LabelNomUniv)
                    .addComponent(NomUniversitat))
                .addContainerGap())
        );

        PanellResultat.setBorder(javax.swing.BorderFactory.createTitledBorder(null, bundle.getString("panell.resultats"), javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N

        TaulaResultat.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Pregunta", "Molt en desacord", "Una mica en desacord", "Indiferent", "Una mica d'acord", "Molt d'acord", "El teu vot"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(TaulaResultat);
        TaulaResultat.getColumnModel().getColumn(0).setResizable(false);
        TaulaResultat.getColumnModel().getColumn(0).setPreferredWidth(120);
        TaulaResultat.getColumnModel().getColumn(1).setResizable(false);
        TaulaResultat.getColumnModel().getColumn(2).setResizable(false);
        TaulaResultat.getColumnModel().getColumn(3).setResizable(false);
        TaulaResultat.getColumnModel().getColumn(4).setResizable(false);
        TaulaResultat.getColumnModel().getColumn(5).setResizable(false);
        TaulaResultat.getColumnModel().getColumn(6).setResizable(false);

        CheckUniversitat.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        CheckUniversitat.setText("Veure només vots d'alumnes de la teva universitat");
        CheckUniversitat.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CheckUniversitatActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout PanellResultatLayout = new javax.swing.GroupLayout(PanellResultat);
        PanellResultat.setLayout(PanellResultatLayout);
        PanellResultatLayout.setHorizontalGroup(
            PanellResultatLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 770, Short.MAX_VALUE)
            .addGroup(PanellResultatLayout.createSequentialGroup()
                .addComponent(CheckUniversitat)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        PanellResultatLayout.setVerticalGroup(
            PanellResultatLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(PanellResultatLayout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(CheckUniversitat)
                .addGap(0, 7, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(PanellEstudiant, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(PanellResultat, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(BotoSortir, javax.swing.GroupLayout.PREFERRED_SIZE, 335, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(PanellEstudiant, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(PanellResultat, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(BotoSortir, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void BotoSortirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BotoSortirActionPerformed
        dispose();
    }//GEN-LAST:event_BotoSortirActionPerformed

    // Es mostrarà a la reixeta els resultats de la universitat de l'estudiant
    // o de totes les universitats
    private void CheckUniversitatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CheckUniversitatActionPerformed
        // Omplirà el jTable TaulaResultat amb els resultats de la BD
        CarregaReixeta();
    }//GEN-LAST:event_CheckUniversitatActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        dispose();
    }//GEN-LAST:event_formWindowClosing

    
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(PantallaResultats.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(PantallaResultats.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(PantallaResultats.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(PantallaResultats.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
//                new PantallaResultats().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BotoSortir;
    private javax.swing.JCheckBox CheckUniversitat;
    private javax.swing.JLabel LabelNomEst;
    private javax.swing.JLabel LabelNomUniv;
    private javax.swing.JLabel NomEstudiant;
    private javax.swing.JLabel NomUniversitat;
    private javax.swing.JPanel PanellEstudiant;
    private javax.swing.JPanel PanellResultat;
    private javax.swing.JTable TaulaResultat;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables
}
